﻿using System;
using System.Collections.Generic;
using System.Text;
using Brc_PaaS.Common.Helper;

namespace Brc_PaaS.Core.Redis
{
    public static class RedisExtension
    {
        private static object _lock = new object();
        /// <summary>
        /// 获取hash对象根据key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="fetchFunc"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public static T GetOrFetchFromHash<T>(this IRedisManager cache, string key, Func<string, T> fetchFunc, TimeSpan? expire = null) where T : class, new()
        {
            var rtn = cache.HashGetAll<T>(key);
            if (EqualityComparer<T>.Default.Equals(rtn, default(T)) && fetchFunc != null)
            {
                lock (_lock) // 加锁
                {
                    if (EqualityComparer<T>.Default.Equals(cache.HashGetAll<T>(key), default(T)))
                    {
                        rtn = fetchFunc(key);
                        if (!EqualityComparer<T>.Default.Equals(rtn, default(T)))
                        {
                            var dic = ToModel<T>.GetDelegate_ToModelDic(rtn);
                            cache.HashMultiSet(key, dic, expire);
                        }
                    }
                }
            }
            return rtn;
        }

        
        /// <summary>
        /// 获取字符串根据key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="fetchFunc"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public static T GetOrFetchString<T>(this IRedisManager cache, string key, Func<string, T> fetchFunc, TimeSpan? expire = null) where T : class, new()
        {
            var rtn = cache.StringGet<T>(key);
            if (EqualityComparer<T>.Default.Equals(rtn, default(T)) && fetchFunc != null)
            {
                lock (_lock) // 加锁
                {
                    if (EqualityComparer<T>.Default.Equals(cache.StringGet<T>(key), default(T)))
                    {
                        rtn = fetchFunc(key);
                        if (!EqualityComparer<T>.Default.Equals(rtn, default(T)))
                        {
                            cache.StringSet<T>(key, rtn, expire);
                        }
                    }
                }
            }
            return rtn;
        }
    }
}
